package com.example.demo.common.utills;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Properties;

public class FileUtil {

    public static String uploadFileSFTP(MultipartFile multipartFile,String name) {
        String fileName=multipartFile.getOriginalFilename();
        int i = fileName.indexOf(".");
        String end=fileName.substring(i,fileName.length());
        String newFileName=name+end;
        FTPClient ftp = new FTPClient();

        try {
            JSch jsch = new JSch();
            // 获取sshSession  账号-ip-端口
            Session sshSession = jsch.getSession("root", "10.54.9.106", 22);
            // 添加密码
            sshSession.setPassword("hjy123!@#");
            Properties sshConfig = new Properties();
            // 严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // 开启sshSession链接
            sshSession.connect();
            // 获取sftp通道
            Channel channel = sshSession.openChannel("sftp");
            // 开启
            channel.connect();
            ChannelSftp sftp = (ChannelSftp) channel;
            // 设置为被动模式
            ftp.enterLocalPassiveMode();
            // 设置上传文件的类型为二进制类型
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 进入到要上传的目录  然后上传文件
            InputStream inputStream = multipartFile.getInputStream();
            if(name.startsWith("报表名称")){
                sftp.cd("/usr/project/data_report");
                // sftp put为上传，get为下载，之后会出一篇下载的代码
                sftp.put(inputStream, newFileName);
                inputStream.close();
                return "/usr/project/data_report"+newFileName;
            }else{
                sftp.cd("/usr/project/share_report");
                // sftp put为上传，get为下载，之后会出一篇下载的代码
                sftp.put(inputStream, newFileName);
                inputStream.close();
                return "/usr/project/share_report"+newFileName;
            }
        } catch (Exception e) {
            System.out.println("FTP服务器 文件上传失败 失败原因："+e.getMessage());
            return null;
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    System.out.println("FTP服务器 关闭失败 失败原因："+e.getMessage());
                }
            }
        }
    }

    public static String uploadFile(MultipartFile multipartFile,String name){
        String uploadPath="";
        String fileName=multipartFile.getOriginalFilename();
        int i = fileName.indexOf(".");
        String end=fileName.substring(i,fileName.length());
        String newFileName=name+end;
       if(name.startsWith("报表名称")){
           uploadPath="/usr/project/data_report/"+newFileName;
           File tempFile = new File(uploadPath);
           if (!tempFile.exists()) {
               boolean il = tempFile.getParentFile().mkdirs();
               if(il){
                   System.out.println("创建层级文件夹成功");
               }
               else
                   System.out.println("创建层级文件夹失败");
               try {
                   boolean ill=tempFile.createNewFile();
                   if(ill){
                       System.out.println("文件创建成功");
                   }
                   else
                    System.out.println("文件创建失败");
               }catch (IOException e) {
                   e.printStackTrace();
               }
           }
           try {
               multipartFile.transferTo(tempFile);
               return uploadPath;
           } catch (IllegalStateException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       else{
           uploadPath="/usr/project/share_report/"+newFileName;
           File tempFile = new File(uploadPath);
           if (!tempFile.exists()) {
               boolean il = tempFile.getParentFile().mkdirs();
               if(il){
                   System.out.println("创建层级文件夹成功");
               }
               System.out.println("创建层级文件夹失败");
               try {
                   boolean ill=tempFile.createNewFile();
                   if(ill){
                       System.out.println("文件创建成功");
                   }
                   System.out.println("文件创建失败");
               }catch (IOException e) {
                   e.printStackTrace();
               }
           }
           try {
               multipartFile.transferTo(tempFile);
               return uploadPath;
           } catch (IllegalStateException e) {
               e.printStackTrace();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return null;
    }


    public static void downloadLocal(HttpServletResponse response,String path) throws FileNotFoundException, UnsupportedEncodingException {
        String[] split = path.split("/");
        String fileName =new String((split[split.length-1]).getBytes("gbk"),"iso8859-1"); // 文件的默认保存名

        // 读到流中
        InputStream inStream = new FileInputStream(path);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("application/json;charset=utf8");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //以流的方式下载
    public static HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

    public static String deleteFile(String path){
        File file=new File(path);
        boolean delete = file.delete();
        if(delete){
            return "success";
        }
        return "fail";
    }
}
